{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[HumanMessage(content='你好!'), AIMessage(content='你好，有什么吩咐呢，我是你的个人小助手?')]\n"
     ]
    }
   ],
   "source": [
    "from langchain.memory import ChatMessageHistory\n",
    "\n",
    "# 创建 ChatMessageHistory 实例\n",
    "history = ChatMessageHistory()\n",
    "\n",
    "# 添加用户消息和 AI 消息\n",
    "history.add_user_message(\"你好!\")\n",
    "history.add_ai_message(\"你好，有什么吩咐呢，我是你的个人小助手?\")\n",
    "\n",
    "# 获取所有消息\n",
    "print(history.messages)\n",
    "# 输出: [HumanMessage(content='你好!'), AIMessage(content='你好，有什么吩咐呢，我是你的个人小助手?')]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'history': 'Human: 你好!\\nAI: 你好，我是你的小助手，有什么需要帮助呢?'}\n"
     ]
    }
   ],
   "source": [
    "from langchain.memory import ConversationBufferMemory\n",
    "\n",
    "# 创建 ConversationBufferMemory 实例\n",
    "memory = ConversationBufferMemory()\n",
    "\n",
    "# 添加用户消息和 AI 消息\n",
    "memory.chat_memory.add_user_message(\"你好!\")\n",
    "memory.chat_memory.add_ai_message(\"你好，我是你的小助手，有什么需要帮助呢?\")\n",
    "\n",
    "# 加载聊天历史\n",
    "chat_history = memory.load_memory_variables({})\n",
    "\n",
    "# 打印聊天历史\n",
    "print(chat_history)\n",
    "# 输出: {'history': 'Human: 你好!\\\\nAI: 你好，我是你的小助手，有什么需要帮助呢?'}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from dotenv import load_dotenv\n",
    "# 加载 .env 文件\n",
    "load_dotenv()  # 默认会加载位于项目根目录的 .env 文件\n",
    "\n",
    "from langchain_community.llms import Tongyi\n",
    "from langchain.chains import ConversationChain\n",
    "from langchain.memory import ConversationBufferMemory\n",
    "\n",
    "# 初始化语言模型\n",
    "\n",
    "# 初始化与 Tongyi 大型语言模型的连接\n",
    "llm = Tongyi(dashscope_api_key=os.getenv(\"DASHSCOPE_API_KEY\"), model_name=\"qwen-plus\")\n",
    "\n",
    "# 创建 ConversationChain 实例，并配置记忆\n",
    "conversation = ConversationChain(\n",
    "    llm=llm,\n",
    "    memory=ConversationBufferMemory(),\n",
    "    verbose=True\n",
    ")\n",
    "\n",
    "# 进行对话\n",
    "response1 = conversation.predict(input=\"中国最大城市在哪里？\")\n",
    "print(response1)\n",
    "\n",
    "response2 = conversation.predict(input=\"中国首都在哪里？\")\n",
    "print(response2)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "chatchat",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.19"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
